﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Chaunce.Web.Core.Helpers
{
    public class ActionFilterHelper
    {
        /// <summary>
        ///获取api请求body值
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetRequestBodyText(HttpRequest request)
        {
            try
            {
                string method = request.Method.ToUpper();
                string requestBodyText = string.Empty;

                if (method == "POST" || method == "PUT" || method == "DELETE")
                {
                    var collection = request.Form;
                    if (collection != null && collection.Count > 0)
                    {
                        //表单提交获取请求值 AddParameter
                        List<string> reqParams = new List<string>();
                        foreach (string key in collection.Keys)
                        {
                            reqParams.Add(string.Format("{0}={1}", key, collection[key]));
                        }
                        requestBodyText = string.Join("&", reqParams);
                    }
                    else
                    {
                        if (request.Body.Length > 0)
                        {
                            //request body 字符串+json 请求获取参数 
                            request.EnableRewind();
                            request.Body.Position = 0;
                            using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8))
                            {
                                requestBodyText = reader.ReadToEnd();
                            }
                        }
                    }
                }
                return requestBodyText;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }
}
